<template>
    <div class="summernoteBox">
      <div :id="id"></div>
    </div>
  </template>
  <script setup>
  import { onMounted, watch, onUnmounted } from 'vue';
  import { customUploadMultiple } from '/@/utils/upload';

  const props = defineProps({
    modelValue: {
      type: String,
      default: "",
    },
    id: {
      type: String,
      default: "summerNote" + new Date().getTime(),
    },
    height: {
      type: [Number, String],
      default: 500
    },
    isEmail: {
      type: Boolean,
      default: false
    }
  });

  const emit = defineEmits(['update:modelValue', 'addAttach', 'useTemplate']);
  
  // 监听 value 属性变化
  watch(() => props.modelValue, (newValue) => {
    // 检查编辑器是否已初始化
    const $summernote = $("#" + props.id)
    if ($summernote.length && $summernote.summernote) {
      // 获取当前编辑器内容
      const currentContent = $summernote.summernote("code");
      // 只有当内容不同时才更新，防止光标位置重置
      if (currentContent !== newValue) {
        $summernote.summernote("code", newValue);
      }
    }
  });

  // 监听高度变化
  watch(() => props.height, (newHeight) => {
    updateHeight(newHeight);
  });

  function updateHeight(height) {
    if ($("#" + props.id).length && $("#" + props.id).summernote) {
      $("#" + props.id).summernote('height', height);
    }
  }

  function TemplateButton(context) {
    let ui = $.summernote.ui;

    // 创建一个按钮
    let button = ui.button({
      contents: '使用模版',
      tooltip: '使用模版',
      click: (e) => emit('useTemplate')
    });

    return button.render();   // 返回按钮的DOM元素
  };

  function AttachButton(context) {
    var ui = $.summernote.ui;

    // 创建一个按钮
    var button = ui.button({
      contents: '添加附件',
      tooltip: '添加附件',
      click: () => {
        emit('addAttach');
      },
    });

    return button.render();   // 返回按钮的DOM元素
  };

  function summernoteInit() {
    const toolbar = [
      ["style", ["style"]],
      ["font", ["bold", "underline", "clear"]],
      ["fontsize", ["fontsize"]],
      ["fontname", ["fontname"]],
      ["color", ["color"]],
      ["para", ["ul", "ol", "paragraph", "height", "hr"]],
      ["table", ["table"]],
      ["insert", ["link", "picture", "video"]],
      ["view", ["fullscreen"]], //"codeview", "help"
    ];

    if (props.isEmail) {
      toolbar.unshift(
        ['template', ['templateButton']],
        ['attachment', ['attachButton']]
      );
    }

    return new Promise((resolve) => {
      const $summernote = $("#" + props.id);
      $summernote.summernote({
        lang: "zh-CN",
        placeholder: "请输入内容",
        height: props.height, // 使用props中的高度
        styleTags: [
          'p',
          {title: 'Striked', tag: 'p', className: 'striked', value: 'p'},
          {title: 'Blockquote', tag: 'blockquote', className: 'blockquote', value: 'blockquote'},
          {title: 'Big Title', tag: 'h1', className: 'bigtitle', value: 'h1'}
        ],
        toolbar,
        fontSizes: [
          "12", "14", "16", "18", "20", "24", "28", "32", "36", "48"
        ],
        fontSizeUnits: ["px"],
        fontNames: [
          // "宋体", "微软雅黑", "楷体", "黑体", "隶书",
          "Arial", "Arial Black", "Comic Sans MS",
          // "Courier New", "Georgia", "Georgia2", "Merriweather"
        ],
        buttons: {
          attachButton: AttachButton,
          templateButton: TemplateButton
        },
        callbacks: {
          onSubmit: function () {},
          onKeyup: function () {},
          onImageUpload: (files) => {
            customUploadMultiple(files).then(res => {
              res.map(item => {
                const imgNode = document.createElement('img');
                imgNode.src = item.url;
                $summernote.summernote('insertNode', imgNode);
              });
            });
          }
        },
      });
      // 初始化完成后立即设置字体为Arial

      $summernote.summernote('fontName', 'Arial');
      resolve();
    });
  }

  function summerNoteChange() {
    emit("update:modelValue", $("#" + props.id).summernote("code"));
  }

  onMounted(() => {
    summernoteInit().then(() => {
      const $summernote = $("#" + props.id);
      $summernote.on(
        "summernote.change",
        function (we, contents, $editable) {
          summerNoteChange();
        }
      );
      $summernote.summernote("code", props.modelValue);
      $summernote.summernote('focus');
    });
  });

  onUnmounted(() => {
    $("#" + props.id).summernote('destroy');
  });
  </script>
  <style scoped  lang="scss" >
  .summernoteBox {
    background-color: #fff;
    :deep(.note-editable) {
      background: #fff;
      font-family: Arial !important; /* 强制设置编辑区域字体 */
    }
    :deep(.note-editable ol li) {
      list-style: decimal;
    }
    :deep(.note-editable ul li) {
      list-style: disc;
    }

    :deep(.note-editable ul) {
      padding: 0 20px;
    }

    :deep(.note-editable ol) {
      padding: 0 20px;
    }

    :deep(.note-btn) {
      border: none;
      background-color: transparent;
      padding: 7px;
    }

    :deep(.note-toolbar) {
      border-radius: 0;
    }

    :deep(.note-statusbar) {
      display: none;
    }

    :deep(.note-editor.note-frame) {
      border: none;
    }
  }
  </style>